package com.axend.aerosense.dev.viewmodel;

import android.app.Activity;
import android.text.TextUtils;

import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.CommonModuleInit;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.bean.RadarBean;
import com.axend.aerosense.common.bean.RadarType;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.ui.LoadingDialog;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.common.util.StringLengthUtils;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.entity.RadarInfoReqBean;
import com.axend.aerosense.dev.entity.RadarNetworkBean;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.ProgressDialogCallBack;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.blankj.utilcode.util.ToastUtils;

import io.reactivex.disposables.Disposable;

public class WavveRadarSettingViewModel extends CustomBaseViewModel<RadarBean> {
    private Disposable disposable;
    public MutableLiveData<String> radarName = new MutableLiveData<>("");
    public MutableLiveData<String> devId = new MutableLiveData<>("");
    public MutableLiveData<String> devVserion = new MutableLiveData<>("");
    public MutableLiveData<String> roomName = new MutableLiveData<>("");
    public MutableLiveData<Boolean> isUpgrading = new MutableLiveData<>(false);
    public MutableLiveData<Boolean> isUpdate = new MutableLiveData<>(false);
    public MutableLiveData<Boolean> tipsState = new MutableLiveData<>(false);  //是否显示Wavve的参数设置、校准功能

    /**
     * 雷达类型： 1：ASSURE 2：WAVVE 3:WAVVE pro
     */
    public MutableLiveData<Integer> radarType = new MutableLiveData<>(RadarType.WAVVE.get());

    public WavveRadarSettingViewModel(IBaseView baseViewImpl, ILoadDataResult<RadarBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
    }

    public void setValue(RadarBean bean){
        if(null != bean && !TextUtils.isEmpty(bean.getRadarUuid())){
            radarName.setValue(bean.getRadarName());
            devId.setValue(bean.getRadarUuid());
            devVserion.setValue("V" + bean.getRadarVersion());
            roomName.setValue(StringLengthUtils.getSimpleString(bean.getRoomName(), 14));
            radarType.setValue(bean.getType().get());
            isUpgrading.setValue(bean.isUpgrading());
            isUpdate.setValue(bean.isUpdate());
        }
    }


    @Override
    public void onLoad() {
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        disposable = EasyHttp.post(UrlApi.URL.GetDevInfo.getUrl())
                .headers("token", token)
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(new RadarNetworkBean(devId.getValue())))
                .execute(new SimpleCallBack<RadarInfoReqBean>() {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        //登录界面不做处理
                        loadDataFail("");
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                        loadDataFail(e.getMessage());
                    }

                    @Override
                    public void onSuccess(RadarInfoReqBean bean) {
                        if (null == bean || null == bean.getRadarInfo() || bean.getRadarInfo().isEmpty()) return;
                        RadarBean radarBean = bean.getRadarInfo().get(0);
                        loadDataSuccess(radarBean);

                        if (radarBean.getType() == RadarType.ASSURE){
                            return;
                        }
                    }
                });
    }

    public void updataName(Activity activity, final String devName, IOperationResult operationResult){
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        disposable = EasyHttp.post(UrlApi.URL.UpdataDevName.getUrl())
                .headers("token", token)
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(new RadarNetworkBean(devId.getValue(), devName)))
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_login_first);
                        //登录界面不做处理
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        ToastUtils.showShort(e.getMessage());
                        if(null != operationResult){
                            operationResult.onFail();
                        }
                    }

                    @Override
                    public void onSuccess(BaseStringBean bean) {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_success);
                        radarName.setValue(devName);
                        if(null != operationResult){
                            operationResult.onSuccess();
                        }
                    }
                });
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (null != disposable && !disposable.isDisposed()){
            disposable.dispose();
        }
    }

    public void deleteRadar(Activity activity, IOperationResult operationResult){
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        disposable = EasyHttp.post(UrlApi.URL.DelRadar.getUrl())
                .headers("token", token)
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(new RadarNetworkBean(devId.getValue())))
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_login_first);
                        //登录界面不做处理
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        ToastUtils.showShort(e.getMessage());
                        if(null != operationResult){
                            operationResult.onFail();
                        }
                    }

                    @Override
                    public void onSuccess(BaseStringBean bean) {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_success);
                        if(null != operationResult){
                            operationResult.onSuccess();
                        }
                    }
                });
    }

    public String getSimpleRadarId(MutableLiveData<String> devId){
        String id = devId.getValue();
        return StringLengthUtils.getSimpleString(id, 15);
    }

    public String getSimpleRadarName(MutableLiveData<String> name){
        String str = name.getValue();
        return StringLengthUtils.getSimpleString(str, 16);
    }

    /**
     * 是否显示标签
     * @param upgrading
     * @param update
     * @return
     */
    public boolean isShowUpdateTag(MutableLiveData<Boolean> upgrading, MutableLiveData<Boolean> update){
        if ((!upgrading.getValue() && !update.getValue())) return false;

        return upgrading.getValue() || update.getValue();
    }

    /**
     * 获取标签文字
     * @param upgrading
     * @param update
     * @return
     */
    public String getUpdateTagString(MutableLiveData<Boolean> upgrading, MutableLiveData<Boolean> update){
        if ((!upgrading.getValue() && !update.getValue())) return "";

        String text = "";

        if (update.getValue()){
            text = CommonModuleInit.getmContext().getString(R.string.dev_new_tag);
        }

        if (upgrading.getValue()){
            text = CommonModuleInit.getmContext().getString(R.string.dev_updating);
        }

        return text;
    }

    /**
     * 1：updating标签 黄色
     * 2: new标签 红色
     * @param upgrading
     * @param update
     * @return
     */
    public int getUpdateTagColor(MutableLiveData<Boolean> upgrading, MutableLiveData<Boolean> update){
        if ((!upgrading.getValue() && !update.getValue())) return 0;

        int result = 0;
        if (update.getValue()){
            result = 2;
        }

        if (upgrading.getValue()){
            result = 1;
        }

        return result;
    }

    /**
     * 是否显示设备参数设置
     * @param radarType
     * @param reveal
     * @return
     */
    public boolean isShowChangeSetting(MutableLiveData<Integer> radarType, MutableLiveData<Boolean> reveal){
        if (radarType.getValue() == 1) return true;
        return radarType.getValue() == 2 && reveal.getValue();
    }


}
